<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link rel="shortcut icon" href="../static/images/local/校标.jpg" />
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>所有新闻</title>
    <link rel="stylesheet" href="../static/layui/css/layui.css"   media="all">
<!--    <link rel="stylesheet" href="../static/css/mySignIn.css"   media="all">-->
    <style>
        body{margin: 10px;}
        .demo-carousel{height: 200px; line-height: 200px; text-align: center;}
    </style>

</head>

<body>
<form class="layui-form" style="display: none" id="present">
    <div class="layui-form-item">
        <label class="layui-form-label">新闻标题</label>
        <div class="layui-input-block">
            <label>
                <input type="text" id="title" name="title" required  lay-verify="required" placeholder="请输入标题" autocomplete="off" class="layui-input">
            </label>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">概述</label>
        <div class="layui-input-block">
            <label>
                <input type="text"  id="dec1" name="title" required  lay-verify="required" placeholder="概述" autocomplete="off" class="layui-input">
            </label>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">类别</label>
        <div class="layui-input-block">
            <label>
                <input type="text"  id="key" name="title" required  lay-verify="required" placeholder="类别" autocomplete="off" class="layui-input">
            </label>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">作者</label>
        <div class="layui-input-block">
            <label>
                <input type="text"  id="author" name="title" required  lay-verify="required" placeholder="作者" autocomplete="off" class="layui-input">
            </label>
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">正文内容</label>
        <div class="layui-input-block">
            <label>
                <textarea name="desc" id="txt"  placeholder="请输入内容" class="layui-textarea"></textarea>
            </label>
        </div>
    </div>
    <style>
        #picture
        {
            max-width: 400px;
            max-height: 300px;
            border: 0px solid #ffffff;
            position: absolute;
            left: 100px;
            margin:auto;
        }
    </style>
    <div class="layui-form-item ">
    <a id="link" target="_blank">
    <img id="picture"  ></a>
    </div>
</form>
<table class="layui-hide" id="demo" lay-filter="test" ></table>
<script>
    const suffix=localStorage.getItem("suffix");
    const prefix=localStorage.getItem("prefix");
    const baseUrl=localStorage.getItem("baseUrl");
    if(sessionStorage.getItem("root")!=="1"&&sessionStorage.getItem("root")!=="0")
{window.alert("请先登录!");window.location.href=prefix+"/logIn"+suffix;}
</script>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-primary layui-border-green" lay-event="search">查找</button>
        <button class="layui-btn layui-btn-primary layui-border-blue" lay-event="refresh">刷新</button>
        <button class="layui-btn layui-btn-primary layui-border-orange" lay-event="getAll">重载全部数据</button>
    </div>
</script>

<script type="text/html" id="barDemo" >
    <a class="layui-btn layui-btn-xs layui-btn layui-btn-normal" lay-event="detail">编辑</a>
    <a class="layui-btn layui-btn-xs layui-btn layui-btn-warm" lay-event="show">详情</a>
    <a class="layui-btn layui-btn-xs" lay-event="save">保存</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
</script>
<script src="../static/layui/layui.js"  ></script>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script>
    let user=JSON.parse(sessionStorage.getItem("user"));
    layui.config({
        version: '1632428048355' //为了更新 js 缓存，可忽略
    });
    //加载模块
    layui.use(function(){ //亦可加载特定模块：layui.use(['layer', 'laydate', function(){
        //得到各种内置组件
        const layer = layui.layer //弹层
            , laypage = layui.laypage //分页
            , table = layui.table //表格
            , element = layui.element //元素操作
        //向你问个好
        layer.msg('你好，亲爱的管理员');

        //监听Tab切换
        element.on('tab(demo)', function(data){
            layer.tips('切换了 '+ data.index +'：'+ this.innerHTML, this, {
                tips: 1
            });
        });
        let root=sessionStorage.getItem("root")
        console.log(root)
        if(root==="1")
        //执行一个 table 实例
        {
            table.render({
                elem: '#demo'
                , height: 620
                , width:1500
                , dataType: 'json'
                , type: "post"
                , url: baseUrl+'/news/getAllNews'
                , parseData: function (res) { //res 即为原始返回的数据
                    let result;
                    if (this.page.curr) {
                         result= res.slice(this.limit * (this.page.curr - 1), this.limit * this.page.curr);
                    } //前端对数据切割分页
                    else {
                        result = res.slice(0, this.limit);
                    }
                    return {
                        "code": 0, //解析接口状态
                        "msg": "", //解析提示文本
                        "count": res.length, //解析数据长度
                        "data": result //解析数据列表
                    };
                }
                , title: '新闻表'
                , page: true //开启分页
                ,limit:10
                ,limits:[5,10,15,20]
                //, defaultToolbar: ['filter', 'print', 'exports']
                , toolbar: '#toolbarDemo' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
                ,totalRow: false //开启合计行
                , cols: [
                    [ //表头
                        {type: 'checkbox', fixed: 'left'}
                        , {field: 'newsTitle', title: '标题', width: '10%' , sort: true, align: 'left', edit: 'text'}
                        , {field: 'newsSort', title: '类别', width: '10%', align: 'center', edit: 'text',sort: true}
                        , {field: 'newsDesc', title: '概述', width: '10%', align: 'center', edit: 'text',sort: true}
                        , {field: 'newsAuthor', title: '作者', width: '10%', align: 'center', sort: true}
                        , {field: 'newsContent', title: '内容', width: '25%', align: 'center', edit: 'text',sort: true}
                        , {field: 'newsDate', title: '发布时间', width: '15%',align: 'center', sort: true}
                        , {fixed: 'right', width: '16.8%',align:'center', toolbar: '#barDemo'}
                    ]
                ]
            });
        }
        else if(root==="0"){
            const user=JSON.parse(sessionStorage.getItem("user")) //解析用户信息为对象
            table.render({
                 elem: '#demo'
                , height: 620
                , width:1500
                , dataType: 'json'
                , type: "post"
                , url: baseUrl+'/news/select_byAuthor'
                , where: {author: user.userName}
                , parseData: function (res) { //res 即为原始返回的数据
                    let result;
                    if (this.page.curr) {
                        result= res.slice(this.limit * (this.page.curr - 1), this.limit * this.page.curr);
                    } //前端对数据切割分页
                    else {
                        result = res.slice(0, this.limit);
                    }
                    return {
                        "code": 0, //解析接口状态
                        "msg": "", //解析提示文本
                        "count": res.length, //解析数据长度
                        "data": result //解析数据列表
                    };
                }
                , title: '新闻表'
                , page: true //开启分页
                ,limit:10
                ,limits:[5,10,15,20]
                , toolbar: '#toolbarDemo'
                 ,totalRow: false //开启合计行
                , cols: [
                    [ //表头
                        {type: 'checkbox', fixed: 'left'}
                        , {field: 'newsTitle', title: '标题', width: '10%', sort: true, align: 'center',edit: 'text'}
                        , {field: 'newsSort', title: '类别', width:'10%', align: 'center', edit: 'text',sort: true}
                        , {field: 'newsDesc', title: '概述', width: '10%', align: 'center', edit: 'text',sort: true}
                        , {field: 'newsAuthor', title: '作者', width: '10%', align: 'center', sort: true}
                        , {field: 'newsContent', title: '内容', width: '25%', align: 'center', edit: 'text',sort: true}
                        , {field: 'newsDate', title: '发布时间', width: '15%', sort: true, align: 'center'}
                        , {fixed: 'right', width: '16.8%', align: 'center', toolbar: '#barDemo'}
                    ]
                ]
            });
        }
        //监听头工具栏事件
        table.on('toolbar(test)', function(obj){
            switch(obj.event){
                case 'refresh':
                    table.reload('demo');
                    break;
                case 'search':
                {
                    {
                        $("#picture").css("display",'none');
                        layui.$('#title').val("")
                        layui.$('#dec1').val("")
                        layui.$('#key').val("")
                        layui.$('#txt').val("")
                        if(root==="1")
                        {layui.$('#author').val(""); //用户只能查询自己的
                         layui.$('#author').removeAttr("readonly");}
                        else layui.$('#author').val(user.userName)
                        layui.$('#title').removeAttr("readonly")
                        layui.$('#picture').attr('src', "");//查找框不显示图片
                        // window.alert("该搜索为模糊查询，请在需要的文本框输入关键词，" +
                        //     "比如查询’王国维‘作品，在作者框输入’维‘")
                        layer.confirm('该搜索为模糊查询，请在需要的文本框输入关键词\n' +
                            '比如查询’王国维‘作品，在作者框输入’维‘,结果取并集', function(index){
                            //do something
                        layer.open({
                            area: ['600px', '500px'],
                            type:1,
                            maxmin:true,
                            // type:2,
                            title:"查找",
                            content:layui.$('#present'),
                            // content:'http://localhost:8080/userShow',
                            end:function (res) {
                                $("#present").css("display",'none');
                            },
                            btn:['查找','取消'],
                            yes:function(index, layero){
                                // 取出输入框的内容
                                const title = layui.$('#title').val();
                                const dec1 = layui.$('#dec1').val();
                                const key= layui.$('#key').val();
                                const txt= layui.$('#txt').val();
                                const author=layui.$('#author').val();
                                const news={
                                    id:"",
                                    newsTitle:title,
                                    newsAuthor:author,
                                    newsDesc:dec1,
                                    newsContent:txt,
                                    newsSort:key,
                                    newsDate:"",
                                    newsImagesPath:"",}//此处不能为null，mysql无法存储
                                table.reload('demo',
                                    {
                                    dataType: 'json'
                                    ,method: "post"
                                    ,url: baseUrl+'/news/select_byWrapper'
                                     ,where: {news :news}
                                      , contentType: 'application/json',
                                        response: {
                                            news:news,
                                        }
                                        , parseData: function (res) { //res 即为原始返回的数据
                                       return {
                                           "code": 0, //解析接口状态
                                            "msg": "", //解析提示文本
                                            "count": res.length, //解析数据长度
                                           "data": res //解析数据列表
                                                };
                                            }} //设定异步数据接口的额外参数
                                )
                                    layer.close(index)
                            }
                        })
                            layer.close(index)
                    });
                    }
                    break;
                }
                case 'getAll':{
                    window.location.reload()
                }
            }
        });

        //监听行工具事件
        table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            const data = obj.data //获得当前行数据
                , layEvent = obj.event; //获得 lay-event 对应的值
            if(layEvent === 'detail')
                {// 修改
                    // 将所要编辑的内容先显示出来
                    console.log(data)
                    $("#picture").css("display",'none');
                    layui.$('#title').val(data.newsTitle)
                    layui.$('#dec1').val(data.newsDesc)
                    layui.$('#key').val(data.newsSort)
                    layui.$('#txt').val(data.newsContent)
                    layui.$('#author').val(data.newsAuthor)
                    $('#author').attr("readonly","readonly")
                    $('#title').attr("readonly","readonly")
                    if(data.newsImagesPath!=="")
                    {   $("#picture").css("display",'block');
                        console.log("测试点1")
                        $('#picture').attr('src', baseUrl+data.newsImagesPath);
                        $('#link').attr('href',baseUrl+data.newsImagesPath);
                    }
                    layer.open({
                        area: ['1000px', '600px'],
                        type:1,
                        maxmin:true,
                        // type:2,
                        title:"编辑",
                        content:layui.$('#present'),
                        // content:'http://localhost:8080/userShow',
                        end:function (res) {
                            layui.$('#picture').attr('src', "");
                            $("#present").css("display",'none');
                        },
                        btn:['保存','取消'],
                        yes:function(index, layero){
                            // 取出输入框的内容
                            const title = layui.$('#title').val();
                            const dec1 = layui.$('#dec1').val();
                            const key= layui.$('#key').val();
                            const txt= layui.$('#txt').val();
                            const news={
                                id:data.id,
                                newsTitle:title,
                                newsAuthor:data.newsAuthor,
                                newsDesc:dec1,
                                newsContent:txt,
                                newsSort:key,
                                newsDate:data.newsDate,
                                newsImagesPath:data.newsImagesPath,}
                            console.log(JSON.stringify(news));
                            console.log(news);
                            // 如果有一项数据未填，则弹出提示框
                            if (check(news)){
                                   $.ajax({
                                    type: 'post',
                                    dataType: "json",
                                    url: baseUrl+'/news/update_news',
                                    headers: {
                                        'Content-Type': 'application/json;charset=utf-8'
                                    },
                                    data: JSON.stringify(news),
                                    success:function (msg) {
                                         if(msg) {layer.msg("保存成功!");
                                             layui.$('#picture').attr('src', "");
                                             table.reload('demo');
                                         }
                                         else layer.alert("保存失败!")
                                    },
                                    error:function ()
                                    {
                                        layer.alert("服务器内部错误!");
                                    }
                                })
                                layer.close(index)
                            }

                        }
                    })

                }
             else if(layEvent === 'delete')
             {
                console.log(data.newsAuthor)
                const news={
                    id:data.id,
                    newsTitle:data.newsTitle,
                    newsAuthor:data.newsAuthor,
                    newsDesc:data.newsDesc,
                    newsContent:data.newsContent,
                    newsSort:data.newsSort,
                    newsDate:data.newsDate,
                    newsImagesPath:data.newsImagesPath,}
                            layer.confirm('真的删除这则新闻么', function(index){
                                $.ajax({
                                    url: baseUrl+"/news/delete_news",
                                    dataType: "json",
                                    type: "post",
                                    headers : {
                                        'Content-Type' : 'application/json;charset=utf-8'
                                    },
                                    data: JSON.stringify(news),
                                    success:function (res) {
                                        console.log(res)
                                        if (res) {alert("删除成功!");
                                            table.reload('demo');}
                                        else alert("删除失败!");
                                    },
                                    error: function ()
                                    {
                                        alert("服务器内部请求错误!");
                                    }
                                })
                                obj.del(); //删除对应行（tr）的DOM结构,类似于刷新
                                layer.close(index);

                            });
                        }
             else if(layEvent === 'save'&&check(data)){
                $.ajax({
                    url: baseUrl+"/news/update_news",
                    dataType: "json",
                    type: "post",
                    headers : {
                        'Content-Type' : 'application/json;charset=utf-8'
                    },
                    data: JSON.stringify(data),
                    success:function (res) {
                        console.log(res)
                        if (res) {layer.msg("保存成功!");}
                        else layer.alert("保存失败!");
                    },
                    error: function ()
                    {
                        alert("服务器内部请求错误!");
                    }
                })
                        }
                      else if(layEvent==="show"){
                           console.log(data)
                          sessionStorage.setItem("news",JSON.stringify(data));
                          console.log(data);
                          console.log(111);
                          window.open(prefix+'/news'+suffix);
            }
                })
            laypage.render({
                elem: 'pageDemo' //分页容器的id
                ,count: 1000 //数据总数
                ,limit: 1//每页显示的数据条数
                ,skin: '#1E9FFF' //自定义选中色值
                //,layout: ['prev', 'page', 'next', 'count', 'limit', 'refresh', 'skip'] //自定义排版
                ,jump: function(obj, first){
                    if(!first){
                        layer.msg('第'+ obj.curr +'页', {offset: 'b'});
                    }
                }
            });
            }
        );
    function check(news) {
        if($.trim(news.newsTitle)==="")
        {
            layer.alert("请输入文章标题!");
            return false;
        }
        if($.trim(news.newsDesc)==="")
        {
            layer.alert("请输入文章简述!");
            return false;
        }
        if($.trim(news.newsSort)==="")
        {
            layer.alert("请输入选择种类!");
            return false;
        }
        if($.trim(news.newsContent)==="")
        {
            layer.alert("请输入文章内容!");
            return false;
        }
        return true;
    }
</script>
</body>
</html>
